package com.ghj.controller;

import com.ghj.pojo.User;
import com.ghj.pojo.Userloginlog;
import com.ghj.pojo.VO.UserVO;
import com.ghj.service.UserService;
import com.ghj.service.UserloginlogService;
import com.ghj.utils.GetCaptcha;
import com.ghj.utils.GetIP;
import com.ghj.utils.SaltUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserloginlogService userloginlogService;
    @Autowired
    private GetIP getIP;
    @Autowired
    private Userloginlog userloginlog;
    @Autowired
     private SaltUtils saltUtils;
    @Autowired
    private GetCaptcha getCaptcha;

    HashMap<String, Boolean> map = new HashMap<>();

    /*
    注册
     */
    @PostMapping("/register")
    public ResponseEntity<Object> register(@RequestBody User user) {
        //判断是不是已经存在用户名
        System.out.println(user.getUserName());
        User isExistUser = userService.findOneByName(user.getUserName());
        if (isExistUser != null) {
            map.put("register", false);
            return ResponseEntity.ok(map);
        } else {
            userService.addUser(user);
            map.put("register", true);
            return ResponseEntity.ok(map);
        }
    }

    /*
    登录
     */
    @PostMapping("/login")
    public ResponseEntity<Object> findOneByName(@RequestBody UserVO userVO, HttpServletRequest request){
        //获取ip
        String loginIp = getIP.getIpAddress(request);
        System.out.println("ip地址"+loginIp);
        User u = userService.findOneByName(userVO.getUsername());
        String userId = u.getUserId();
        System.out.println("id="+userId);
        String s = saltUtils.getSalt();
        userloginlog.setLoginId(s);
        userloginlog.setUserId(userId);
        userloginlog.setLoginIp(loginIp);


        //获得当前用户
        Subject subject = SecurityUtils.getSubject();
        // System.out.println(userVO);
        //拿取盐值
        String salt = userService.findOneByName(userVO.getUsername()).getSalt();
        System.out.println("盐值："+salt);
        String password = new Md5Hash(userVO.getPassword(), salt).toBase64();
        userVO.setPassword(password);
        System.out.println("加密后密码："+userVO.getPassword());
        //对用户名和密码进行封装，令牌
        UsernamePasswordToken token = new UsernamePasswordToken(userVO.getUsername(),userVO.getPassword());
        //设置记住我
        //token.setRememberMe(true);

        try {
            //执行登录操作
            subject.login(token); //将令牌提交到realm进行验证
            userloginlogService.addUserLogin(userloginlog);
            map.put("token",true);
            return ResponseEntity.ok(map);
        }catch (UnknownAccountException e){
            //用户名不在
            map.put("token",false);
            return ResponseEntity.ok(map);
        }catch(IncorrectCredentialsException e){
            //密码错误
            map.put("token",false);
            return ResponseEntity.ok(map);
        }
    }
    @GetMapping("/getcode")
    public ResponseEntity<Object> getCaptcha(HttpServletRequest request, HttpServletResponse response){
        String captcha = getCaptcha.captcha(request, response);
        return ResponseEntity.ok(captcha);
    }
}
